// 交通事件处理平台主脚本

// DOM元素加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    updateCurrentTime();
    setInterval(updateCurrentTime, 1000);
    renderEvents('all');

    // 绑定事件监听
    document.getElementById('refresh-btn').addEventListener('click', function() {
        showLoading();
        setTimeout(() => {
            renderEvents('all');
            hideLoading();
            showToast('事件已刷新', 'success');
        }, 800);
    });

    document.querySelectorAll('#filter-dropdown .dropdown-item').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            const filter = this.getAttribute('data-filter');
            renderEvents(filter);
        });
    });

    document.getElementById('back-to-list').addEventListener('click', function() {
        document.getElementById('event-detail-view').style.display = 'none';
        document.getElementById('event-list-view').style.display = 'block';
    });
});

// 更新当前时间
function updateCurrentTime() {
    const now = new Date();
    document.getElementById('current-time').textContent = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 渲染事件列表
function renderEvents(filter) {
    const container = document.getElementById('events-container');
    container.innerHTML = '';

    let filteredEvents = eventsDB;

    // 根据筛选条件过滤事件
    if (filter === 'high') {
        filteredEvents = eventsDB.filter(event => event.event_info.severity >= 0.7);
    } else if (filter === 'medium') {
        filteredEvents = eventsDB.filter(event => event.event_info.severity >= 0.3 && event.event_info.severity < 0.7);
    } else if (filter === 'low') {
        filteredEvents = eventsDB.filter(event => event.event_info.severity < 0.3);
    }

    // 渲染事件卡片
    filteredEvents.forEach(event => {
        const severityClass = event.event_info.severity >= 0.7 ? 'severity-high' :
                             (event.event_info.severity >= 0.3 ? 'severity-medium' : 'severity-low');

        const severityText = event.event_info.severity >= 0.7 ? '高' :
                            (event.event_info.severity >= 0.3 ? '中' : '低');

        const severityBadgeClass = event.event_info.severity >= 0.7 ? 'bg-danger' :
                                 (event.event_info.severity >= 0.3 ? 'bg-warning' : 'bg-success');

        const card = document.createElement('div');
        card.className = `card event-card ${severityClass}`;
        card.innerHTML = `
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h5 class="card-title">${event.event_info.type}</h5>
                        <p class="card-text">
                            <i class="bi bi-geo-alt me-1"></i> ${event.location.area_type}
                        </p>
                        <p class="card-text">
                            <i class="bi bi-clock me-1"></i> ${new Date(event.timestamp).toLocaleString('zh-CN')}
                        </p>
                    </div>
                    <span class="badge ${severityBadgeClass}">优先级: ${severityText}</span>
                </div>
                ${event.event_info.has_injury ? `
                <div class="mt-2 alert alert-danger p-2">
                    <i class="bi bi-exclamation-circle me-1"></i> 涉及人员受伤
                </div>
                ` : ''}
            </div>
        `;

        card.addEventListener('click', () => showEventDetail(event.id));
        container.appendChild(card);
    });

    // 如果没有事件
    if (filteredEvents.length === 0) {
        container.innerHTML = '<div class="alert alert-info">没有找到符合条件的事件</div>';
    }
}

// 显示事件详情
function showEventDetail(eventId) {
    const event = eventsDB.find(e => e.id === eventId);
    if (!event) return;

    // 填充事件详情数据
    document.getElementById('event-id').textContent = event.id;
    document.getElementById('event-time').textContent = new Date(event.timestamp).toLocaleString('zh-CN');
    document.getElementById('event-location').textContent = `${event.location.longitude.toFixed(6)}, ${event.location.latitude.toFixed(6)}`;
    document.getElementById('event-area-type').textContent = event.location.area_type;
    document.getElementById('event-type').textContent = event.event_info.type;
    document.getElementById('event-alert-level').textContent = event.alert_level;

    // 更新进度条
    updateProgressBar('confidence-bar', 'confidence-value', event.event_info.confidence);
    updateProgressBar('severity-bar', 'severity-value', event.event_info.severity);
    updateProgressBar('crowd-bar', 'crowd-value', event.event_info.crowd_density);
    updateProgressBar('impact-bar', 'impact-value', event.predicted_impact?.traffic_impact || 0);

    // 显示/隐藏受伤提示
    document.getElementById('injury-alert').style.display = event.event_info.has_injury ? 'block' : 'none';

    // 渲染处理方案
    renderProcessingOptions(event.processing_options || []);

    // 渲染资源分配
    renderResourceAllocation(event.resource_allocation || []);

    // 渲染时间线
    renderTimeline(event.timeline || []);

    // 渲染预计影响
    renderPredictedImpact(event.predicted_impact || {});

    // 初始化地图
    initMap(event.location.longitude, event.location.latitude);

    // 切换视图
    document.getElementById('event-list-view').style.display = 'none';
    document.getElementById('event-detail-view').style.display = 'block';
}

// 更新进度条
function updateProgressBar(barId, valueId, value) {
    const percentage = Math.round(value * 100);
    document.getElementById(barId).style.width = `${percentage}%`;
    document.getElementById(valueId).textContent = percentage;
}

// 渲染处理方案
function renderProcessingOptions(options) {
    const container = document.getElementById('processing-options');
    container.innerHTML = '';

    if (options.length === 0) {
        container.innerHTML = '<p>暂无处理方案</p>';
        return;
    }

    options.forEach(option => {
        const levelClass = option.level === 'high' ? 'level-high' :
                         (option.level === 'medium' ? 'level-medium' : 'level-low');

        const item = document.createElement('div');
        item.className = 'mb-3';
        item.innerHTML = `
            <div class="d-flex align-items-center">
                <h6 class="mb-0">${option.name}</h6>
                <span class="impact-level ${levelClass}">${option.level === 'high' ? '高' : option.level === 'medium' ? '中' : '低'}</span>
            </div>
            <p class="text-muted">${option.level_desc}</p>
            <div class="progress">
                <div class="progress-bar" role="progressbar" style="width: ${Math.round(option.necessity * 100)}%"
                     aria-valuenow="${Math.round(option.necessity * 100)}" aria-valuemin="0" aria-valuemax="100">
                    必要性: ${Math.round(option.necessity * 100)}%
                </div>
            </div>
        `;
        container.appendChild(item);
    });
}

// 渲染资源分配
function renderResourceAllocation(resources) {
    const container = document.getElementById('resource-allocation');
    container.innerHTML = '';

    if (resources.length === 0) {
        container.innerHTML = '<p>暂无资源分配信息</p>';
        return;
    }

    resources.forEach(resource => {
        const badge = document.createElement('span');
        badge.className = 'badge bg-primary resource-badge';
        badge.textContent = resource;
        container.appendChild(badge);
    });
}

// 渲染时间线
function renderTimeline(timeline) {
    const container = document.getElementById('impact-timeline');
    container.innerHTML = '';

    if (timeline.length === 0) {
        container.innerHTML = '<p>暂无时间线信息</p>';
        return;
    }

    timeline.forEach(item => {
        const timelineItem = document.createElement('div');
        timelineItem.className = 'timeline-item';
        timelineItem.innerHTML = `
            <div class="timeline-time">${new Date(item.time).toLocaleTimeString('zh-CN')}</div>
            <div class="timeline-content">
                <strong>${item.action}</strong>
                <span class="badge ${item.status === '完成' ? 'bg-success' : 'bg-warning'} ms-2">${item.status}</span>
            </div>
        `;
        container.appendChild(timelineItem);
    });
}

// 渲染预计影响
function renderPredictedImpact(impact) {
    document.getElementById('traffic-impact').textContent = impact.traffic_impact || 0;
    document.getElementById('impact-duration').textContent = impact.duration || 0;
    document.getElementById('impact-radius').textContent = impact.radius || 0;

    // 设置影响消息
    let message = '暂无影响评估信息';
    if (impact.traffic_impact >= 0.7) {
        message = '此事件将对周边交通造成严重影响，请立即处理！';
    } else if (impact.traffic_impact >= 0.3) {
        message = '此事件将对周边交通造成一定影响，建议尽快处理。';
    } else if (impact.traffic_impact > 0) {
        message = '此事件对周边交通影响较小，可按常规流程处理。';
    }
    document.getElementById('impact-message').textContent = message;

    // 初始化图表
    initImpactChart(impact);
}

// 初始化影响图表
function initImpactChart(impact) {
    const ctx = document.getElementById('impact-chart').getContext('2d');

    // 销毁已存在的图表
    if (window.impactChart) {
        window.impactChart.destroy();
    }

    window.impactChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['交通影响', '持续时间(分钟)', '影响范围(公里)'],
            datasets: [{
                label: '事件影响评估',
                data: [
                    (impact.traffic_impact || 0) * 100,
                    impact.duration || 0,
                    (impact.radius || 0) * 10
                ],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.5)',
                    'rgba(255, 99, 132, 0.5)',
                    'rgba(75, 192, 192, 0.5)'
                ],
                borderColor: [
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 99, 132, 1)',
                    'rgba(75, 192, 192, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 初始化地图
function initMap(lng, lat) {
    // 销毁已存在的地图实例
    if (window.map) {
        window.map.destroy();
    }

    // 创建新地图实例
    window.map = new AMap.Map('map-container', {
        zoom: 15,
        center: [lng, lat]
    });

    // 添加标记
    const marker = new AMap.Marker({
        position: [lng, lat],
        icon: new AMap.Icon({
            size: new AMap.Size(30, 40),
            image: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23dc3545"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>',
            imageSize: new AMap.Size(30, 40)
        })
    });

    map.add(marker);
}

// 显示加载状态
function showLoading() {
    document.querySelector('.loading-overlay').style.display = 'flex';
}

// 隐藏加载状态
function hideLoading() {
    document.querySelector('.loading-overlay').style.display = 'none';
}

// 显示提示消息
function showToast(message, type = 'info') {
    const container = document.getElementById('toast-container');
    const toastId = `toast-${Date.now()}`;

    const toast = document.createElement('div');
    toast.id = toastId;
    toast.className = `toast align-items-center text-white bg-${type} border-0 fade show`;
    toast.role = 'alert';
    toast.ariaLive = 'assertive';
    toast.ariaAtomic = 'true';
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;

    container.appendChild(toast);

    // 3秒后自动关闭
    setTimeout(() => {
        const toastEl = document.getElementById(toastId);
        if (toastEl) {
            const toastInstance = new bootstrap.Toast(toastEl);
            toastInstance.hide();
            // 移除元素
            setTimeout(() => toastEl.remove(), 500);
        }
    }, 3000);
}